<script setup lang="ts">
import { reactive, ref } from "vue"
import { ElMessage, type FormRules } from "element-plus"
import { doSplitApi } from "@/api/billv2"
// import { doSplitApi } from "@/api/bill"

//#region 表单
const formLabelWidth = "120px"
const loading = ref(false)
const formRef = ref<any>(null)
const form = reactive({
  bill_id: 0,
  inventory_id: 0,
  dismantle_money: 0,
  billRange: 1
})
const rules = reactive<FormRules>({
  dismantle_money: [{ required: true, message: "请输入拆分金额", trigger: "blur" }],
  billRange: [
    {
      required: true,
      message: "请选择子票区间",
      trigger: "change"
    }
  ]
})

const cancelForm = () => {
  dialogFormVisible.value = false
  form.bill_id = 0
  form.inventory_id = 0
  form.dismantle_money = 0
  form.billRange = 1
  loading.value = false
}
const handleClose = () => {
  cancelForm()
  emit("DialogClose", true)
}
const emit = defineEmits(["DialogClose"])
const onClick = async () => {
  formRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true
      await doSplitApi(form)
        .then(() => {
          ElMessage.success("新增成功")
          handleClose()
        })
        .finally(() => {
          dialogFormVisible.value = false
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
//#endregion

//暴露给父组件
// 定义一个 ref 变量 dialogFormVisible，用于存储对话框的显示状态
const dialogFormVisible = ref(false)
// 定义一个函数 showClick，用于在点击某个行时显示对话框
function showClick(row: any) {
  // 将当前行的 bill_id 和 inventory_id 赋值给 form
  form.bill_id = row.bill_id
  form.inventory_id = row.inventory_id
  // 设置对话框的显示状态为 true
  dialogFormVisible.value = true
}
// 导出函数 showClick
defineExpose({ showClick })
</script>

<template>
  <el-dialog
    destroy-on-close
    draggable
    v-model="dialogFormVisible"
    :before-close="handleClose"
    title="拆分"
    width="30%"
  >
    <el-form ref="formRef" label-position="top" :model="form" :rules="rules" :label-width="formLabelWidth">
      <el-form-item label="拆分金额(元)" prop="dismantle_money">
        <el-input-number v-model="form.dismantle_money" :min="1" />
      </el-form-item>
      <el-form-item label="子票区间" prop="billRange">
        <el-radio-group v-model="form.billRange">
          <el-radio :label="1">前面拆分</el-radio>
          <el-radio :label="2">后面拆分</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="demo-drawer__footer">
      <!-- <el-button @click="handleClose">关闭</el-button> -->
      <el-button type="primary" :loading="loading" @click="onClick">提交</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.demo-drawer__footer {
  display: flex;
  justify-content: end;
}
</style>
